package com.android.process.messenger

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.lib.messenger.AndroidMessenger
import com.android.lib.messenger.MessageCallback
import kotlinx.android.synthetic.main.activity_test_1.*

class TestActivity1 : AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_1)
        AndroidMessenger.subscribe("ServiceToActivity1", object : MessageCallback {
            override fun onMessageCallBack(data: Bundle?) {
                val test = data?.getString("test")
                val text = "TestActivity1 接收到消息$test"
                Toast.makeText(this@TestActivity1, text, Toast.LENGTH_SHORT).show()
                Log.e("35hwm", "1---$text")
                tv1.text = text
            }
        })
        AndroidMessenger.subscribe("Activity2ToActivity1", object : MessageCallback {
            override fun onMessageCallBack(data: Bundle?) {
                val test = data?.getString("test")
                val text = "TestActivity1 接收到消息$test"
                Toast.makeText(this@TestActivity1, text, Toast.LENGTH_SHORT).show()
                Log.e("35hwm", "2---$text")
                tv1.text = text
            }
        })
        button1.setOnClickListener {
            //发送消息到另外一个进程的服务
            val bundle = Bundle()
            bundle.putString("test", "TestActivity1 发送消息到服务")
            AndroidMessenger.post("service", bundle)
        }
        button2.setOnClickListener {
            val intent = Intent(this, TestActivity2::class.java)
            startActivity(intent)
        }
        val intent = Intent(this, TestService::class.java)
        startService(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        AndroidMessenger.unSubscribe("ServiceToActivity1")
        AndroidMessenger.unSubscribe("Activity2ToActivity1")
    }

}